package com.thraex.lucene.chapter1;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * @Author 鬼王
 * @Date 2019/05/06 13:23
 */
public class Searcher {

    public static void main(String[] args) throws IOException, ParseException {
        int len = 2;
        if (args.length != len) {
            throw new IllegalArgumentException("Usage: java " +
                Searcher.class.getName() + " <index dir> <query>");
        }

        Scanner sc = new Scanner(System.in);
        System.out.println("Please input query string:");
        String q = sc.nextLine();

        //search(args[0], args[1]);
        search(args[0], q);
    }

    /**
     * @param indexDir Parse provided index directory
     * @param q Parse provided query string
     */
    public static void search(String indexDir, String q) throws IOException, ParseException {
        // Note 3: Open index
        Directory dir = FSDirectory.open(new File(indexDir));
        IndexSearcher is = new IndexSearcher(dir);

        // Note 4: Parse query
        QueryParser parser = new QueryParser(Version.LUCENE_30, "contents",
                new StandardAnalyzer(Version.LUCENE_30));

        Query query = parser.parse(q);
        long start = System.currentTimeMillis();

        // Note 5: Search index
        TopDocs hits = is.search(query, 10);

        long end = System.currentTimeMillis();

        // Note 6: Write search stats
        System.err.println("Found " + hits.totalHits +
            " document(s) (in " + (end - start) +
            " milliseconds) that matched query '" +
            q + "':");

        for (ScoreDoc scoreDoc : hits.scoreDocs) {
            // Note 7: Retrieve matching document
            Document doc = is.doc(scoreDoc.doc);
            // Note 8: Display filename
            System.out.println(doc.get("fullpath"));
        }

        // Note 9: Close IndexSearcher
        is.close();
    }

}
